本篇同步發文在個人Blog: 一袋.NET要扛幾樓?打造容器化的ASP.NET Core網站!系列文章 - (22) 建立購物車系統 - 5
在CartApi專案右鍵=>加入=>Dokcer支援,選擇目標平台Linux,將會在根目錄新增Dockerfile檔案,需要再手動修改,變成下方的內容。其內容主要功能是在Docker容器內載入NET Core SDK編譯我們的程式碼,將編譯後的目錄檔案複製到Runtime環境的/app目錄,再用NET Core Runtime執行購物車服務。
FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /code
EXPOSE 80
COPY . .
RUN dotnet restore
RUN dotnet publish -o /out/ -c Release
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
COPY --from=build /out /app/
WORKDIR /app
ENTRYPOINT ["dotnet", "CartApi.dll"]
在docker-compose.yml加入CartApi的container,如下方的yml。主要的參數包含:
version: "3.4"
networks:
frontend:
backend:
services:
webmvc:
build:
context: .\src\Presentation\WebMvc
dockerfile: Dockerfile
environment:
- CatalogUrl=http://catalog
- IdentityUrl=https://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7101
- CallBackUrl=http://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7500/
container_name: rpgwebmvc
ports:
- "7500:80"
networks:
- frontend
depends_on:
- catalog
- auth
catalog:
build:
context: .\src\Services\CatalogApi
dockerfile: Dockerfile
image: rpgshop/catalog
environment:
- DatabaseServer=mssqlserver
- DatabaseName=CatalogDb
- DatabaseUser=sa
- DatabasePassword=JustTest!
- ExternalCatalogBaseUrl=http://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7000
container_name: rpgcatalogapi
ports:
- "7000:80"
networks:
- backend
- frontend
depends_on:
- mssqlserver
auth:
build:
context: .\src\Services\AuthApi
dockerfile: Dockerfile
image: rpgshop/auth
environment:
- MvcClient=http://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7500
- DatabaseServer=mssqlserver
- DatabaseName=AuthDb
- DatabaseUser=sa
- DatabasePassword=JustTest!
- ExternalCatalogBaseUrl=http://${RPGSHOP_EXTERNAL_DNS_NAME_OR_IP}:7000
- ASPNETCORE_URLS=http://+:80;https://+:443
- ASPNETCORE_Kestrel__Certificates__Default__Password=crypticpassword
- ASPNETCORE_Kestrel__Certificates__Default__Path=./AuthApi.pfx
container_name: rpgauthapi
ports:
- "7100:80"
- "7101:443"
networks:
- backend
- frontend
depends_on:
- mssqlserver
cart:
build:
context: .\src\Services\CartApi
dockerfile: Dockerfile
image: rpgshop/cart
environment:
- ConnectionString=cart.data
container_name: rpgcartapi
ports:
- "7400:80"
networks:
- backend
- frontend
depends_on:
- cart.data
mssqlserver:
image: "microsoft/mssql-server-linux:latest"
ports:
- "1445:1433"
container_name: rpgmssqlcontainer
environment:
- ACCEPT_EULA=Y
- SA_PASSWORD=JustTest!
networks:
- backend
cart.data:
image: redis
ports:
- "6377:6379"
networks:
- backend
目前只先執行購物車服務,所以用cmd在docker-compose.yml所在位置輸入指令:
docker-compose build
docker-compose up cart.data cart
執行完後,在瀏覽器輸入http://docker.for.win.localhost:7400/swagger ,顯示Swagger對API的功能,如圖1。
圖1